package com.example.demo.repository;

import com.example.demo.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
    Optional<Student> findByStudentNo(String studentNo);
    Optional<Student> findByUserId(Long userId);
    
    // 根据学号搜索学生
    List<Student> findByStudentNoContaining(String studentNo);
    
    // 根据学号搜索学生（分页）
    Page<Student> findByStudentNoContaining(String studentNo, Pageable pageable);
    
    // 根据姓名搜索学生（分页）
    @Query("SELECT s FROM Student s JOIN User u ON s.userId = u.id WHERE u.realName LIKE %:name%")
    Page<Student> findByNameContaining(@Param("name") String name, Pageable pageable);
    
    // 多条件搜索学生（分页）
    @Query("SELECT s FROM Student s JOIN User u ON s.userId = u.id WHERE " +
           "(:studentNo IS NULL OR s.studentNo LIKE %:studentNo%) AND " +
           "(:name IS NULL OR u.realName LIKE %:name%)")
    Page<Student> findByStudentNoContainingAndNameContaining(
        @Param("studentNo") String studentNo, 
        @Param("name") String name, 
        Pageable pageable);
        
    // 根据班级ID获取学生
    @Query("SELECT s FROM Student s WHERE s.classId = :classId")
    List<Student> findByClassId(@Param("classId") Long classId);
    
    // 根据班级ID获取学生（分页）
    @Query("SELECT s FROM Student s WHERE s.classId = :classId")
    Page<Student> findByClassId(@Param("classId") Long classId, Pageable pageable);
}